<?php

/**
 */

namespace App\Api\CatchOrder;

use Monolog\Logger;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\RotatingFileHandler;
use Illuminate\Support\Facades\DB;

class Pdd
{
    protected $log;
    protected $root;
    protected $config;
    protected $version;
    protected $url_code;
    protected $url_api;
    protected $access_token;
    protected $client_id;
    protected $interval_time;
    protected $interval_time_int;
    public function __construct($access_token, $client_id, $time = 5)
    {
        $this->config = config('pdd');
        $this->log = new Logger('Pdd');
        $this->log->pushHandler(
            (new RotatingFileHandler(storage_path('/logs/Pdd.log'), 14, Logger::DEBUG, true, 0777))->setFormatter(new LineFormatter(null, null, true, true))
        );

        $this->root = new Logger('PddRootLog');
        $this->root->pushHandler(
            (new RotatingFileHandler(storage_path('/logs/PddRootLog.log'), 14, Logger::DEBUG, true, 0777))->setFormatter(new LineFormatter(null, null, true, true))
        );
        $this->version = 'V1'; // 版本
        $this->url_code = 'https://fuwu.pinduoduo.com/service-market/auth';  // 获取code
        $this->url_api = 'http://gw-api.pinduoduo.com/api/router'; // 请求连接
        $this->access_token = $access_token;
        $this->client_id = $client_id;
        $this->interval_time = $time * 60;
        $this->interval_time_int = 60; // 往前 或 往后 差个 一分钟 以防漏单
    }


    /**
     * @desc 同步
     * @return boolean
     */
    public function async()
    {
        // 获取增量订单
        set_time_limit(300);

        $time2  =  time();

        // $time3  =   strtotime("-12 hour");
        // 间隔时间
        $time1  =   $time2 - $this->interval_time;

        /* $res    =   DB::table('flow_order_async')->where([['async_time', '>', $time1]])->first();
        if($res){ return true; }*/

        // $url    =   $this->config['url_api'];
        $url = $this->url_api;
        $data['access_token']       =   $this->access_token;
        $data['client_id']          =   $this->client_id;
        $data['data_type']          =   'JSON';
        $data['end_updated_at']     =   $time2;
        $data['is_lucky_flag']      =   '0';
        $data['order_status']       =   '1';
        $data['page']               =   '1';
        $data['refund_status']      =   '1';
        $data['start_updated_at']   =   $time1;
        $data['timestamp']          =   $time2;
        $data['type']               =   'pdd.order.number.list.increment.get';
        $data['version']            =   $this->version;
        $data['sign']               =   $this->getSign($data);

        $header =   ["Content-Type: application/json", "Accept: application/json"];

        $data       =   json_encode($data);
        $content    =   get_url_content($url, $data, $header);
        $json       =   json_decode($content, true);

        $this->root->info('同步订单库---' . $content);
        if (!$json || !isset($json['order_sn_increment_get_response']) || !isset($json['order_sn_increment_get_response']['total_count']) || $json['order_sn_increment_get_response']['total_count'] < 1) {
            $this->root->info('同步订单库失败---' . $content);
            return false;
        }
        $add    =   [];
        $sd =   DB::table('syspara')->where('name', 'pdd_sd')->first();
        $sd_detail  =   isset($sd->val) && $sd->val != '' ? explode(',', $sd->val) : [];
        foreach ($json['order_sn_increment_get_response']['order_sn_list'] as $n) {
            if (!isset($n['order_sn'])) {
                $this->root->info('缺少订单信息---');
                continue;
            }
            if (DB::table('order')->where('pdd_order', $n['order_sn'])->first()) {
                continue;
            }
            if (!isset($n['item_list']) || !isset($n['item_list'][0])) {
                $this->root->info('缺少商品信息---' . $n['order_sn']);
                continue;
            }

            $product =   DB::table('wlkpackage')->where('product_id', $n['item_list'][0]['goods_id'])->first();
            $this->root->info('goods_id---' . $n['item_list'][0]['goods_id']);
            if (!$product) {
                $this->root->info('缺少套餐信息---' . $n['order_sn']);
                continue;
            }


            $aCode =   DB::table('address_code')
                ->where([
                    ['areas_name', 'like', mb_substr($n['town'], 0, 2, 'utf-8') . '%'],
                    ['city_name', 'like', mb_substr($n['city'], 0, 2, 'utf-8') . '%'],
                    ['provinces_name', 'like', mb_substr($n['province'], 0, 2, 'utf-8') . '%']
                ])
                ->first();

            if (!$aCode) {
                $this->root->info('缺少省市区地址码---' . $n['order_sn']);
                continue;
            }
            $orderInfo  =   $this->getOrderInfo($n['order_sn']);
            if (!$orderInfo) {
                $this->root->info('获取用户身份信息失败---' . $n['order_sn']);
                continue;
            }
            $n['id_card_name'] = $orderInfo['id_card_name'];
            $n['id_card_num'] = $orderInfo['id_card_num'];
            $userInfo   =   $this->getUserInfo($n);
            if (!$userInfo) {
                $this->root->info('解密失败---' . $n['order_sn']);
                continue;
            }

            $time   =   date('Y-m-d H:i:s');
            if (!DB::table('order')->where('pdd_order', $n['order_sn'])->first()) {
                $order_status   = 1;
                $error_log      = '';

                if ($sd_detail) {
                    foreach ($sd_detail as $value) {
                        if (strpos($userInfo['addr'], $value) !== false) {
                            $order_status   =   8;
                            $error_log      =   '拼多多刷单直接成功不再提交';
                            break;
                        }
                    }
                }
                $cut = mb_strpos($userInfo['addr'], $n['town']) + mb_strlen($n['town']);
                $userInfo['addr'] = mb_substr($userInfo['addr'], $cut);
                $add[]  =   [
                    'pdd_order'     =>  $n['order_sn'],
                    'user_name'     =>  $userInfo['true_name'],
                    'user_card'     =>  $userInfo['idcard'],
                    'province'      =>  $n['province'],
                    'province_code' =>  $product->channel_name == 'SdYidong' ? $aCode->provinces_yd_cord : $aCode->provinces,
                    'province_all_code' =>  $aCode->provinces_code,
                    'city'          =>  $n['city'],
                    'city_code'     =>  $product->channel_name == 'SdYidong' ? $aCode->city_yd_cord : $aCode->city,
                    'city_all_code' =>  $aCode->city_code,
                    'area'          =>  $n['town'],
                    'pdd_at'        =>  $n['created_time'],
                    'area_all_code' =>  $aCode->areas_code,
                    'address'       =>  $userInfo['addr'],
                    'phone'         =>  $userInfo['phone'],
                    'pdd_good'      =>  $n['item_list'][0]['sku_id'],
                    'pdd_name'      =>  $n['item_list'][0]['goods_name'],
                    'pdc_name'      =>  $product->showname,
                    'goods_id'      =>  $product->productids,
                    'goods_name'    =>  $product->name,
                    'channel_name'  =>  $product->channel_name,
                    'goods_page'    =>  $product->nodate,
                    'order_status'  =>  $order_status,
                    'error_log'     =>  $error_log,
                    'created_at'    =>  $time,
                ];
            }
        }
        if ($add) DB::table('order')->insert($add);
        DB::table('flow_order_async')->where('id', 1)->update(['async_time' => $time2]);
        return 1;
    }

    function getSign($params)
    {
        $arrSign    =   [];
        ksort($params);
        $rule       =   $this->config['rule'];
        foreach ($params as $k => $v) {
            if (in_array($k, $rule) || $v == '') {
                continue;
            }

            if (is_array($v)) {
                $v = json_encode($v);
            }

            $arrSign[] = trim($k) . trim($v);
        }
        $strSign    =   implode('', $arrSign);
        $sign       =   strtoupper(md5($this->config['client_secret'] . $strSign . $this->config['client_secret']));
        return $sign;
    }

    public function getAes($params)
    {
        $text   =   http_build_query($params, ' ', '&');
        $sign   =   openssl_encrypt($text, 'AES-256-ECB', $this->config['accessKey']);
        return $sign;
    }
    // 解密
    public function getUserInfo($list)
    {
        $c      =   json_encode([
            ['data_tag' => $list['order_sn'], 'encrypted_data' => $list['id_card_name']],
            ['data_tag' => $list['order_sn'], 'encrypted_data' => $list['id_card_num']],
            ['data_tag' => $list['order_sn'], 'encrypted_data' => $list['receiver_phone']],
            ['data_tag' => $list['order_sn'], 'encrypted_data' => $list['address']],
            ['data_tag' => $list['order_sn'], 'encrypted_data' => $list['receiver_name']],
        ]);

        // $url    =   $this->config['url_api'];
        $url    = $this->url_api;
        $data['access_token']       =   $this->access_token;
        $data['client_id']          =   $this->client_id;
        $data['data_type']          =   'JSON';
        $data['timestamp']          =   time();
        $data['type']               =   'pdd.open.decrypt.batch';
        $data['data_list']          =   $c;
        $data['sign']               =   $this->getSign($data);
        //dd($data);
        $header =   ["Content-Type: application/json", "Accept: application/json"];

        $data       =   json_encode($data);

        $content    =   get_url_content($url, $data, $header);
        $json       =   json_decode($content, true);

        if (!$json || !isset($json['open_decrypt_batch_response']) || !isset($json['open_decrypt_batch_response']['data_decrypt_list'][4])) {
            $this->root->info('订单解密失败---' . $content);
            return false;
        }

        return [
            'true_name' => $json['open_decrypt_batch_response']['data_decrypt_list'][0]['decrypted_data'],
            'idcard' => $json['open_decrypt_batch_response']['data_decrypt_list'][1]['decrypted_data'],
            'phone' => $json['open_decrypt_batch_response']['data_decrypt_list'][2]['decrypted_data'],
            'addr' => $json['open_decrypt_batch_response']['data_decrypt_list'][3]['decrypted_data'],
            'name' => $json['open_decrypt_batch_response']['data_decrypt_list'][4]['decrypted_data'],
        ];
    }

    public function getOrderInfo($order_sn)
    {

        $url    =   $this->config['url_api'];
        $url   = $this->url_api;
        $data['access_token']       =   $this->access_token;
        $data['client_id']          =   $this->client_id;
        $data['data_type']          =   'JSON';
        $data['timestamp']          =   time();
        $data['type']               =   'pdd.order.virtual.information.get';
        $data['order_sn']           =   $order_sn;
        $data['sign']               =   $this->getSign($data);
        //dd($data);
        $header =   ["Content-Type: application/json", "Accept: application/json"];

        $data       =   json_encode($data);

        $content    =   get_url_content($url, $data, $header);
        $json       =   json_decode($content, true);

        if (!$json || !isset($json['order_virtual_information_response'])) {
            $this->root->info('订单获取失败---' . $content);
            return false;
        }

        return [
            'id_card_name' => $json['order_virtual_information_response']['id_card_name'],
            'id_card_num' => $json['order_virtual_information_response']['id_card_num'],
        ];
    }

    function getAcToken()
    {
        $time   =   time();
        $token  =   DB::table('order_access_token')->where('id', 1)->first();
        if ($token) {
            return $token->access_token;
        }

        $code   =   DB::table('order_code')->where('id', 1)->first();
        $data['type']      =   'pdd.pop.auth.token.create';
        $data['client_id'] =   $this->client_id;
        $data['timestamp'] =   $time;
        $data['code']      =   $code->code;
        $data['data_type'] =   'JSON';
        $data['sign']      =   $this->getSign($data);
        $url               =   $this->config['url_api'] . '?' . http_build_query($data, ' ', '&');
        $content           =   get_url_content($url, []);
        $json              =   json_decode($content, true);

        if (!$json || !isset($json['pop_auth_token_create_response']) || !isset($json['pop_auth_token_create_response']['access_token'])) {
            $this->root->info('获取token失败---' . $content);
            return false;
        }
        $time2 = 60 * 60 * 24 * 364 + $time;

        DB::table('order_access_token')->where('id', 1)->update(['access_token' => $json['pop_auth_token_create_response']['access_token'], 'token_time' => $time2]);

        return $json['pop_auth_token_create_response']['access_token'];
    }

    function getCode()
    {
        $url = $this->config['url_code'] . '?' . 'response_type=code&client_id=' . $this->config['client_id'] . '&redirect_uri=' . $this->config['url_re'];
        $content    =   get_url_content($url, []);
        $this->log->info($url);
        dd(111111);
    }

    /**
     * 所有订单
     * 间隔时间 * 5 
     * 这就是意味着 获取五次接口后
     *
     * @return void
     */
    public function orderList()
    {
        set_time_limit(300);

        $time2  =   time();
        $time1  =   $time2 - 60 * 60 * 24;

        // $url    =   $this->config['url_api'];
        $url = $this->url_api;
        $data['access_token']       =   $this->access_token;
        $data['client_id']          =   $this->client_id;
        $data['data_type']          =   'JSON';
        $data['end_confirm_at']     =   $time2;
        $data['order_status']       =   '5';
        $data['page']               =   '1';
        $data['trade_type']         =   '0';
        $data['refund_status']      =   '5';
        $data['start_confirm_at']   =   $time1;
        $data['timestamp']          =   $time2;
        $data['type']               =   'pdd.order.list.get';
        $data['version']            =   $this->version;
        $data['sign']               =   $this->getSign($data);

        $header =   ["Content-Type: application/json", "Accept: application/json"];

        $data       =   json_encode($data);
        $content    =   get_url_content($url, $data, $header);
        $json       =   json_decode($content, true);
        dd($json);
    }
    // 发货
    public function subOrder($order)
    {
        $time   =   time();
        $url    =  $this->url_api;
        $data['access_token']       =   $this->access_token;
        $data['client_id']          =   $this->client_id;
        $data['data_type']          =   'JSON';
        $data['timestamp']          =   $time;
        $data['type']               =   'pdd.logistics.online.send';
        $data['order_sn']           =   $order->pdd_order;
        $data['logistics_id']       =   $order->wuliu_number;
        $data['tracking_number']    =   $order->wuliu_gongsi;
        $data['version']            =   $this->version;
        $data['sign']               =   $this->getSign($data);

        $header =   ["Content-Type: application/json", "Accept: application/json"];

        $data       =   json_encode($data);
        $content    =   get_url_content($url, $data, $header);
        $json       =   json_decode($content, true);
        dd($json);
    }
}
